<template>
  <!-- 外层容器，使用flex布局 -->
  <view class="page-container">
    <!-- 固定区域 -->
    <view class="fixed-area">
      <!-- 状态栏的占位 -->
      <view class="headers">
        <view class="boxAndTop" :style="{paddingTop:statusBarHeight+'px'}"></view>
        <view style="display: flex;justify-content: space-between;align-items: center;">
          <view class="left-titles">
          </view>
        </view>
        <view @click="upateUserWechat()"
              style="width: 100%;padding:100rpx 50rpx;box-sizing: border-box;padding-bottom: 50rpx;display: flex;align-items: center;">
          <u-avatar :src="userInfo.avatarUrl" size="60"></u-avatar>
          <view style="margin-left: 30rpx;color: #fff">
            <view style="font-weight: bolder;font-size: 20px; color:#25772f">
              {{ userInfo.nickname || '请登录' }}
            </view>
            <view style="display: flex;">
              <view style="display: flex;font-size: 14px;align-items: center;" @click.stop="bind_community">
                <span style="margin-left: 5rpx;color: #666" v-show="userInfo.nickname">点击编辑头像和昵称</span>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="userInfo">
        <view style="display: flex; justify-content: space-between; padding: 0 50rpx; align-items: center; width: 100%">
          <u-tabs
              :activeStyle="{ color: '#000', fontWeight: '800' }"
              padding="30px"
              lineWidth="30"
              lineColor="#25772f"
              :list="tab_list"
              @click="tab_click"
              :current="tab_active"
          ></u-tabs>

          <!-- 搜索区域（始终显示搜索图标，点击后右侧展开输入框） -->
          <view class="search-container">
            <!-- 搜索图标（始终显示） -->
            <u-icon name="search" size="25" color="#333" @click="focusSearch" v-if="!showSearch" class="search-icon"></u-icon>
            <u-icon name="search" size="25" color="#333" @click="doSearch" v-else class="search-icon"></u-icon>
            <!-- 输入框（点击后展开） -->
            <view class="search-input-wrapper" :class="{ 'active': showSearch }">
              <u-input
                  v-model="searchKeyword"
                  placeholder="请输入"
                  border="none"
                  @confirm="doSearch"
                  @blur="onSearchBlur"
                  v-if="showSearch"
              />
              <u-icon
                  v-if="showSearch"
                  name="close-circle"
                  size="19"
                  color="#999"
                  @click="cancelSearch"
                  class="search-close-icon"
              />
            </view>
          </view>
        </view>
      </view>
      
      <!-- 在"上报"tab时显示二级tabs并固定 -->
      <view v-show="tab_active == 0" class="sub-tabs-fixed">
        <u-tabs :activeStyle="{
                  color: '#000',
                  fontWeight: '800'
                }" font-size="16" padding="15px" lineWidth="0" :list="tab_list1" @click="tab_click1"
                :current="information_form.auditStatus"></u-tabs>
      </view>
    </view>

    <!-- 滚动区域 -->
    <scroll-view class="scroll-area" scroll-y="true" @scrolltolower="onReachBottomFunc">
      <informationList2 :auditStatus="information_form.auditStatus" ref="information_list" :user_info="userInfo"
                        @click_item="to_information"></informationList2>
      <u-loadmore :marginTop="30" :status="page_loding" loading-text="加载中..." loadingIcon="spinner"
                  v-if="!(page_loding == 'nomore' && $u.test.isEmpty(information_list))"/>
    </scroll-view>

    <!-- 悬浮图片（固定在右下角） -->
    <view class="floating-image" @click="gotoFb()">
      <image src="/static/shangbao.png" mode="aspectFill"></image>
    </view>
    
    <!-- 个人收藏悬浮按钮 -->
    <view class="floating-favorites" @click="goToFavorites()">
      <u-icon name="heart-fill" size="18" color="#fff"></u-icon>
      <text class="favorites-text">收藏音乐</text>
    </view>
    <authuserInfo ref="auth_userInfo"></authuserInfo>
    <!-- 引入自定义tabBar -->
    <custom-tabbar
        :currentIndex="2"
    ></custom-tabbar>
  </view>
</template>

<script>
import authuserInfo from "@/components/auth-userinfo/auth-userinfo.vue"
import informationList2 from "@/components/information-list/information-list2.vue"
import CustomTabbar from '@/components/tabbar/tabbar.vue'

export default {
  components: {
    authuserInfo,
    informationList2,
    CustomTabbar,
  },
  data() {
    return {
	  loginFlag:false,
      showSearch: false, // 控制搜索框显示
      searchKeyword: '', // 搜索关键词
      page_loding: 'nomore',
      statusBarHeight: 0,
      titleBarHeight: 0,
      tab_active: 0,

      approvedNum: 0,
      rejectedNum: 0,
      pendingNum: 0,
      upReport: 0,
      visited: 0,
      wishlist: 0,
      information_form: {
        page: 0,
        auditStatus: 0, //三个状态 approved 通过 rejected 不通过  pending 审核中
        lat: '',
        lon: '',
        distance: '5',
        size: '7',
      },
      userInfo: [],
      information_list: [],
    }
  },
  computed: {
    tab_list1() {
      return [
        {name: '已通过 ' + this.approvedNum, value: 0},
        {name: '审核中 ' + this.pendingNum, value: 1},
        {name: '未通过 ' + this.rejectedNum, value: 2}
      ]
    },
    tab_list() {
      return [
        {name: '上报 ' + this.upReport, value: 0},
        {name: '想去 ' + this.wishlist, value: 1},
        {name: '去过 ' + this.visited, value: 2}
      ]
    }
  },
  onShow() {
    this.init()
  },
  onPullDownRefresh() {
    uni.showLoading({
      title: "加载中"
    })
    this.init()
  },
  onLoad() {
    //获取状态栏的高度
    let systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight
    let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    this.titleBarHeight = (menuButtonInfo.top - this.statusBarHeight) * 2 + menuButtonInfo.height
  },
  methods: {
	  async onReachBottomFunc() {
		  if(this.page_loding=='loadmore'){
			  await this.get_information()
		  }
	  },
    to_information(item) {
      console.log(item,)
      if(this.information_form.auditStatus == 0){
        uni.navigateTo({
          url: "/packageB/information/information?information_id=" + item.id + '&lat=' + item.latitude + '&lon=' + item.longitude
        })
      }else {
        // 执行页面跳转
        uni.switchTab({
          url: "../release/release",
          fail: (err) => {
            console.error('tab跳转失败:', err)
          }
        })
        // 设置全局参数
        getApp().globalData.tabParams = {
          information_id: item.id,
          type: 'home'
        }
      }
    },
    // 点击搜索图标（聚焦输入框）
    focusSearch() {
      this.showSearch = true;
      // 需要手动触发输入框聚焦（uniapp可能需要setTimeout）
      setTimeout(() => {
        const input = this.$refs.searchInput?.$el?.querySelector('input');
        if (input) input.focus();
      }, 100);
    },

    // 执行搜索
    doSearch() {
      if (!this.searchKeyword.trim()) return;
      // 执行搜索逻辑...
      this.page_loding = 'loading';
      this.information_list = [];
      this.$refs.information_list.foreFlowView();
      this.information_form.page = 0;
      this.get_information();
    },

    // 重置搜索
    resetSearch() {
      delete this.information_form.keyword;
      this.page_loding = 'loading';
      this.information_list = [];
      this.$refs.information_list.foreFlowView();
      this.information_form.page = 0;
      this.get_information();
    },
    tab_click(item) {
      this.tab_active = item.index
      this.page_loding = 'loading'
      this.information_list = [];
      this.$refs.information_list.foreFlowView(); // 清空瀑布流
      this.information_form.page = 0;
      this.get_information()
    },
    tab_click1(item) {
      this.information_form.auditStatus = item.index
      this.page_loding = 'loading'
      this.information_list = [];
      this.$refs.information_list.foreFlowView(); // 清空瀑布流
      this.information_form.page = 0;
      this.get_information()
    },
    /**
     * 初始化方法
     */
    async init() {
      console.log('====>', this.information_form)
      this.information_form.auditStatus = 0;
     // this.page_loding = 'loading'  // 设置加载状态
      this.information_list = [];
      this.$refs.information_list.foreFlowView(); // 清空瀑布流
      this.information_form.page = 0;
      this.searchKeyword = ''
      uni.authorize({
        scope: 'scope.userLocation',
        success: async () => {
          let location = await this.$get_location()
          console.log(8888, location)
          this.information_form.lat = location.latitude
          this.information_form.lon = location.longitude

          this.is_notopen = false

          let token = uni.getStorageSync('token')
		  console.log('token',token)
          if (token) {
           await this.getUserInfo()
			if(this.loginFlag){
				this.getUpReportCount()
				this.getmineCount()
				this.get_information(location)
			}
          }

          this.loading = false
          setTimeout(() => {
            this.is_loading = false
          }, 500)
        },
        fail: () => {
          let _this = this
          uni.showModal({
            title: '授权提示',
            content: '我们需要您的位置信息用于匹配您最近的服务，如您不授权位置信息，将无法展示相关内容，建议您授权位置信息！',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (res) => {
                    if (res.authSetting['scope.userLocation'] === true) {
                      _this.init()
                    }
                  }
                });
              } else if (res.cancel) {
                this.community_name = '未授权位置'
                this.is_notopen = true
                this.is_loading = false
              }
            }
          });
        }
      })

      uni.hideLoading()
    },
    /**
     * 获取信息列表
     */
    get_information(location) {
      console.log(5555, location)
      if (location) {
        this.information_form.lat = location.latitude
        this.information_form.lon = location.longitude
      }
      return new Promise((suc, err) => {

        if (this.tab_active == 0) {
          let auditStatusType = ['approved', 'pending', 'rejected']//三个状态 approved 通过 rejected 不通过  pending 审核中
          let new_information_form = JSON.parse(JSON.stringify(this.information_form))
          new_information_form.auditStatus = auditStatusType[this.information_form.auditStatus]
          new_information_form.keyword = this.searchKeyword
          this.getUpReportCount()
          this.getmineCount()
          this.$http.to_http('search/upReportSelect', new_information_form, 'GET', false).then(res => {
            res = res.data
            if (res.code != 200) {
              return uni.showToast({
                title: "系统维护中",
                icon: "none"
              })
            }
            if (res.data.content.length > 0) {
              this.information_form.page++;
            }
			console.log('totalPages=',res.data.totalPages,'page=',this.information_form.page)
            if (res.data.totalPages > this.information_form.page) {
              this.page_loding = 'loadmore'
            } else {
              setTimeout(() => {
                this.page_loding = 'nomore'
              }, 1000)
            }
            res.data.content.forEach(el => {
              this.information_list.push(el)
            })
            // 触底加载时追加数据，而不是重新初始化
            if (this.information_form.page === 0) {
              // 第一页数据，重新初始化
              this.$refs.information_list.init(this.information_list)
            } else {
              // 后续页面，追加数据
              this.$refs.information_list.appendData(res.data.content)
            }
			console.log('page_loding=',this.page_loding)
            suc(true);
          }).catch(async err => {
            suc(true);
          })
        } else {

          let auditStatusType = ['approved', 'wishlist', 'visited']//三个状态 approved 通过 rejected 不通过  pending 审核中
          let new_information_form = JSON.parse(JSON.stringify(this.information_form))
          new_information_form.relationType = auditStatusType[this.tab_active]
          new_information_form.keyword = this.searchKeyword
          delete new_information_form.auditStatus
          this.$http.to_http('search/relationList', new_information_form, 'GET', false).then(res => {
            res = res.data
            if (res.code != 200) {
              return uni.showToast({
                title: "系统维护中",
                icon: "none"
              })
            }
            console.log(2222, res)
            if (res.data.content.length > 0) {
              this.information_form.page++;
            }
			console.log('totalPages=',res.data.totalPages,'page=',this.information_form.page)
            if (res.data.totalPages > this.information_form.page) {
              this.page_loding = 'loadmore'
            } else {
              setTimeout(() => {
                this.page_loding = 'nomore'
              }, 1000)
            }
            res.data.content.forEach(el => {
              this.information_list.push(el)
            })
            // 触底加载时追加数据，而不是重新初始化
            if (this.information_form.page === 0) {
              // 第一页数据，重新初始化
              this.$refs.information_list.init(this.information_list)
            } else {
              // 后续页面，追加数据
              this.$refs.information_list.appendData(res.data.content)
            }
			console.log('page_loding=',this.page_loding)
			
            suc(true);
          }).catch(async err => {
            suc(true);
          })
        }
      })
    },

    gotoFb() {
      console.log(22222)
      uni.switchTab({
        url: '/pages/release/release' // 注意要使用绝对路径
      });
	  // 设置全局参数
	  getApp().globalData.tabParams = {
	    information_id: '',
	    type: 'addForm'
	  }
    },
    /**
     * 绑定小区
     */
    bind_community() {
      uni.navigateTo({
        url: "/pages/user/info"
      })
    },

    upateUserWechat() {
      if (!this.loginFlag) {
        uni.$on('authUserInfoCallback', (data) => {
          setTimeout(() => {
            this.getUserInfo('更新中')
            this.get_information()
          }, 2000)
        })
        this.$refs.auth_userInfo.openAuth()
      }
    },
    /**
     * 用户信息
     */
    getUserInfo(is_loading = false) {
      return new Promise((suc, err) => {
        this.$http.to_http('system/miniUser/getByToken', {}, 'GET', is_loading).then(res => {
          res = res.data
          if (res.code == 200) {
			this.loginFlag=true
            this.userInfo = res.data
            uni.setStorageSync('userInfo', res.data)
          }
          uni.hideLoading()
          suc(true);
        })
      })
    },

    getUpReportCount(is_loading = false) {
      return new Promise((suc, err) => {
        this.$http.to_http('system/tree/count', {}, 'POST', is_loading).then(res => {
          res = res.data
          if (res.code != 200) {
            return uni.showToast({
              title: "获取数据失败",
              icon: "none"
            })
          }
          
          // 重置计数器
          this.approvedNum = 0;
          this.rejectedNum = 0;
          this.pendingNum = 0;
          
          // 解析新的数据格式
          if (res.data && Array.isArray(res.data)) {
            res.data.forEach(item => {
              switch (item.auditStatus) {
                case 'approved':
                  this.approvedNum = item.count || 0;
                  break;
                case 'rejected':
                  this.rejectedNum = item.count || 0;
                  break;
                case 'pending':
                  this.pendingNum = item.count || 0;
                  break;
              }
            });
          }
          
          uni.hideLoading()
          suc(true);
        })
      })
    },
    getmineCount(is_loading = false) {
      return new Promise((suc, err) => {
        this.$http.to_http('search/mineCount', {}, 'POST', is_loading).then(res => {
          res = res.data
          if (res.code != 200) {
            return uni.showToast({
              title: "获取数据失败",
              icon: "none"
            })
          }
          this.upReport = res.data.upReport
          this.visited = res.data.visited
          this.wishlist = res.data.wishlist
          uni.hideLoading()
          suc(true);
        })
      })
    },
    // 跳转到个人收藏页面
    goToFavorites() {
      uni.navigateTo({
        url: '/packageB/nature-sound/nature-sound?type=favorites'
      })
    },
  }
}
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f3f4f6;
}

.fixed-area {
  flex-shrink: 0; /* 防止固定区域被压缩 */
}

.scroll-area {
  flex: 1; /* 占据剩余空间 */
  overflow-y: auto;
  padding-bottom: 130rpx; /* 为tabbar留出空间 */
}

.bg {
  background-color: #f7f7f7f7;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.headers {
  background-image: url('http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/e29a1cf5-94dc-4dec-b0ae-23dbe68d50eb.png?Expires=4907190348&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=E6j8QwejatiDDlQyeftJd%2F4ozUE%3D');
  height: 450rpx;
  width: 100%;
  background-size: cover;
}

.left-titles {
  width: 42%;
  text-align: left;
  color: #fff;
  font-weight: bolder;
  padding: 10rpx 35rpx;
  box-sizing: border-box;
}

.titles {
  width: 58%;
  text-align: left;
  color: #fff;
  font-weight: bolder;
  padding: 10rpx 0;
  box-sizing: border-box;
}

.userInfo {
  width: 100%;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 50rpx 50rpx 0 0;
  position: relative;
  margin-top: -50rpx;
  padding: 15rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
  z-index: 10;
}

/* 二级tabs固定样式 */
.sub-tabs-fixed {
  background-color: #FFFFFF;
  padding-left: 50rpx;
  position: relative;
  z-index: 10;
}

.floating-image {
  position: fixed;
  right: 20px;
  bottom: 60px;
  width: 60px;
  height: 60px;
  z-index: 999;
  border-radius: 50%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.floating-image image {
  width: 100%;
  height: 100%;
}

/* 个人收藏悬浮按钮样式 */
.floating-favorites {
  position: fixed;
  right: 20px;
  bottom: 140px;
  width: 65px;
  height: 65px;
  z-index: 999;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff6b6b, #ff4757);
  box-shadow: 0 4px 12px rgba(255, 71, 87, 0.3);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  overflow: hidden;
  cursor: pointer;
}

.floating-favorites:active {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(255, 71, 87, 0.5);
}

.favorites-text {
  color: #fff;
  font-size: 16rpx;
  font-weight: 500;
  text-align: center;
  margin-top: 2rpx;
  line-height: 1;
}

/* 搜索容器 */
.search-container {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  max-width: 250rpx; /* 增加搜索容器的最大宽度 */
}

/* 搜索图标样式增强 */
.search-icon {
  font-weight: bold;
  text-shadow: 0.5px 0.5px 0 #333, -0.5px -0.5px 0 #333, 0.5px -0.5px 0 #333, -0.5px 0.5px 0 #333;
}

/* 输入框容器（默认隐藏） */
.search-input-wrapper {
  width: 0;
  overflow: hidden;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
}

/* 输入框展开状态 */
.search-input-wrapper.active {
  width: 220rpx; /* 调整输入框宽度 */
  margin-left: 10rpx;
}

/* 输入框样式 */
.u-input {
  background-color: #f5f5f5;
  border-radius: 20rpx;
  padding: 0 20rpx;
  height: 60rpx;
  font-size: 14px;
  flex: 1;
}

/* 关闭按钮 */
.search-close-icon {
  margin-left: 30rpx;
  margin-right: 10rpx; /* 添加右边距确保不会超出边界 */
}
</style>